<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">
        <span @click="saveState">首页</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item :to="{ path: '/goods' }">商品列表</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->

      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏区域 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndexString"
          :tab-position="'left'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格/元" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number" @mousewheel.native.prevent></el-input>
            </el-form-item>
            <el-form-item label="商品库存(斤)" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="1">
            <!-- action表示图片要上传到的后台API地址 -->
            <el-upload
              :action="uploadURL"
              :auto-upload="false"
              :on-change="getFile"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :multiple="true"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <!-- <div slot="tip" class="el-upload__tip">
                只能上传jpg/png文件，且不超过500kb
              </div> -->
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="2">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce" :options="editorOption">
            </quill-editor>
          </el-tab-pane>
          <el-button class="elBtn" type="success" @click="next"
            >下一步</el-button
          >
        </el-tabs>
      </el-form>
    </el-card>

    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="30%">
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      activeIndex: 0,
      activeIndexString: "0",
      //   添加商品的表单数据对象
      addForm: {
        goods_name: "",
        goods_price: "",
        goods_number: "",
        //商品分类
        goods_cat: [],
        // 图片数组
        pics: [],
        // 商品的详情描述
        goods_introduce:''
      },
      addFormRules: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品库存", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      cateList: [],
      cateProps: {
        label: "cat_name",
        value: "_id",
      },
      //   上传图片的URL地址
      uploadURL: "http://localhost:3000/api/upload",
      // 图片上传组件的headers请求头对象
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 图片列表
      imgList: [],
      // 预览
      previewPath: "",
      previewVisible: false,
      editorOption: {
        placeholder: "编辑商品内容",
      },
    };
  },
  watch: {
    activeIndex(val) {
      this.activeIndexString = val.toString();
    },
    activeIndexString(val) {
      this.activeIndex = Number(val);
    },
  },
  created() {
    this.getCateList();
  },
  methods: {
    saveState() {
      window.sessionStorage.setItem("activePath", "/welcome");
    },
    // 获取所有商品分类数据
    async getCateList() {
      const res = await this.$http.get("/categories");
      if (res.status === 200) {
        this.cateList = res.data;
        // console.log(this.cateList);
      }
    },
    // 级联选择器选中项变化，会触发这个函数
    handleChange() {
      console.log(this.addForm.goods_cat);
    },
    // 检验表格
    formValidate() {
      let p = new Promise((resolve, reject) => {
        this.$refs.addFormRef.validate((valid) => {
          valid ? resolve() : reject();
        });
      });
      return p;
    },
    async beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == 0) {
        return await this.formValidate();
      }
      if(oldActiveName == 1 && activeName == 2){
        if(this.imgList.length == 0){
          this.$message.error("请上传图片！");
          return new Promise((resolve, reject)=>reject())
        }
      }
    },
    next() {
      this.$refs.addFormRef.validate(async(valid) => {
        if (valid) {
          if (this.activeIndex === 0) {
            this.activeIndex++;
          } else if (this.activeIndex === 1 && this.imgList.length == 0) {
            this.$message.error("请上传图片！");
          } else if (this.activeIndex === 1 && this.imgList.length != 0) {
            this.addForm.pics = [];
            for (var i = 0; i < this.imgList.length; i++) {
              this.getBase64(this.imgList[i].raw).then((res) => {
                console.log(res);
                // 1.拼接得到一个图片信息对象
                const picInfo = { pic: res };
                // 2.将图片信息对象，push到pics数组中
                this.addForm.pics.push(picInfo);
              });
            }
            this.activeIndex++;
          }else{
            // 深拷贝
            const form = _.cloneDeep(this.addForm)
            form.goods_cat = form.goods_cat.join(',')
            console.log(form);
            // 发起请求添加商品
            const res = await this.$http.post('/goods',form)
            console.log(res)
            if(res.status === 200){
              this.$message.success('添加商品成功！')
              this.$router.push('/goods')
            }
          }
        }
      });
    },
    tabClicked() {
      console.log(this.activeIndex);
    },
    getBase64(file) {
      return new Promise(function (resolve, reject) {
        let reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 获取图片
    getFile(file, fileList) {
      console.log(file, fileList);
      this.imgList = fileList;
    },
    // 处理图片预览效果
    handlePreview(file) {
      console.log(file);
      this.getBase64(file.raw).then((res) => {
        this.previewPath = res;
        this.previewVisible = true;
      });
    },
    // 处理移除图片的操作
    handleRemove() {},
  },
};
</script>

<style lang="less" scoped>
.elBtn {
  margin-top:15px;
}
.previewImg {
  width: 100%;
}
</style>